<template>
  <div class="chart-container">
    <div id="chinamap" class="chinamap" />
  </div>
</template>

<script>
import { loadBMap } from "@/utils/map";
import dataApi from "@/api/data";
export default {
  props:{
    parent_items:Array
  },
  data() {
    return {
      chart: null,
      maxValue: 1000,
      minValue: 0,
      visualItem: "森林覆盖率",
      year: 2013,
      dataList: [],
      items: [],
      years: ["2013", "2014", "2015", "2016", "2017", "2018"],
      animationTimer: null,
      selectedCity:''
    };
  },
  watch:{
    parent_items(val){
      this.$nextTick(() => {
        loadBMap("D19qfIlsnlt3hXZQ226041j39LtQ6Voh").then(() => {
          this.items = val
          this.initchart();
        });
      });
    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   loadBMap("D19qfIlsnlt3hXZQ226041j39LtQ6Voh").then(() => {
    //     dataApi.getData().then((res) => {
    //       this.items = res.data.items;
    //       // 初始化图表
    //       this.initchart();
    //       this.animation();
    //     });
    //   });
    // });
  },
  beforeDestroy(){
      clearInterval(this.animationTimer)
  },
  methods: {
    animation() {
      let that = this;
      let items = this.items;
      //console.log(items);
      this.animationTimer = setInterval(() => {
        let currentYear = Number(that.year)
        let dataList = that.getDataList(items,currentYear)
        let option = that.setChart(that)
        that.chart.setOption(option)
        currentYear = (currentYear+1) > 2018 ? 2013 : currentYear+1;
        that.year = currentYear;
      }, 1000);
    },
    initchart() {
      this.chart = this.$echarts.init(document.getElementById("chinamap"));
      let option = this.setChart(this);
      this.chart.setOption(option);

      this.animation();

      // 注册点击事件
      this.chart.on('click', (param)=>{
          var selected = param.name
          this.selectedCity = selected
          //console.log(this.selectedCity);
          this.$emit('updata-selected-city',this.selectedCity)
      })

      // 注册窗口变化回调函数
      window.addEventListener("resize",()=>{
          this.resizeChart()
      })
    },
    setChart(that) {
      var dataList = that.getDataList(that.items,that.year)
      var option = {
        backgroundColor:"#282a36",
        title:{
            text: '全国'+that.visualItem + "统计 " + that.year + " 年",
            textStyle: {
	        	  fontWeight: 'bold',              //标题颜色
	        	  color: 'rgb(238, 197, 102)'
	      	  },
            subtext: "国家林草局统计年鉴",
            subtextStyle:{
              fontWeight: 'normal',              //标题颜色
	        	  color: 'rgb(238, 197, 102)'
            },
            sublink: "#",
            left: "center",
        },
        tooltip: {
          trigger: "item",
          showDelay: 0,
          transitionDuration: 0.2,
          formatter: function (params) {
            //保留整数
            //var value = (params.value + '').split('.')
            //value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
            return (
              params.seriesName +
              "<br/>" +
              params.name +
              ": " +
              params.value +
              "%"
            );
          },
        },
        visualMap: {
          min: 0,
          max: 100,
          align: "auto",
          left: "left",
          bottom: "10%",
          orient: "horizontal",
          text: ["高", "低"],
          textStyle:{
            color:'#fff'
          },
          inRange: {
            color: ["orangered", "yellow", "green"],
          },
          calculable: false,
          show: true,
        },
        geo: {
          map: "china",
          roam: false,
          zoom: 1.0,
          label: {
            normal: {
              show: true,
              fontSize: "10",
              color: "rgba(0,0,0,0.7)",
            },
          },
          itemStyle: {
            normal: {
              borderColor: "rgba(0, 0, 0, 0.2)",
            },
            emphasis: {
              areaColor: "#F3B329",
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              shadowBlur: 20,
              borderWidth: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
        series: [
          {
            name: that.visualItem,
            type: "map",
            geoIndex: 0,
            data: dataList,
          },
        ],
      };
      return option;
    },
    getMax(dataList) {
      var max = Number.MIN_VALUE;
      for (let i = 0; i < dataList.length; i++) {
        max =
          Number(dataList[i].value) > max
            ? Number(dataList[i].value)
            : max;
      }
      return max;
    },
    getMin(dataList) {
      var min = Number.MAX_VALUE;
      for (let i = 0; i < dataList.length; i++) {
        min =
          Number(dataList[i].value) < min
            ? Number(dataList[i].value)
            : min;
      }
      return min;
    },
    getDataList(items,year) {
       let res = [] 
      for (let i = 0; i < items.length; i++) {
        if (Number(items[i]["年份"]) === year) {
          res.push({
            name: items[i].city.replace(/\s+/g, ""),
            value: Number(items[i][this.visualItem]),
          });
        }
      }
      return res;
    },
    resizeChart(){
        this.chart.resize()
    }
  },
};
</script>

<style>
.chinamap{
    width:100%;
    height: calc(60vh)
}
</style>